/**
 * DWR form support load/add/save method
 *
 * @author liuhz
 */
CQCIS.form.DWRForm = function(config){
    this.waitMsgTarget = true;
    Ext.apply(this, config);
    
    this.baseParams = this.baseParams ||
    {};
    this.extendParams = [];
    this.doing = false;
    CQCIS.form.DWRForm.superclass.constructor.call(this);
};

Ext.extend(CQCIS.form.DWRForm, Ext.FormPanel, {
    /**
     * @cfg {dwr} DWR call
     *
     * <pre>
     * 属性      描述
     * ---------dwr----------------
     * load     加载
     * save     保存
     * update   更新
     * </pre>
     *
     * @cfg {metas} Fields metas
     *
     * <pre>
     * 属性
     * 描述
     * ------recordHeaders----------
     * field    字段
     * desc     描述
     * type     字段类型
     * mapping  映射
     * ------fieldMetas-------------
     * xtype    Ext form field component
     *          [textfield,datefield,timefield,numberfield,checkbox,radio,combo,textarea,hidden]
     *          [text, date, time, num, check, radio, combo, area, hidden, rcombo, acombo, treecombo] + [pwd pwdv]
     * vtype    [email,zhcn,number,int]
     * vaules   值序列 for checkbox, radio
     * obj      Object or config of ext form field
     * -----------------------------
     * </pre>
     */
    initState: Ext.emptyFn,
    saveState: Ext.emptyFn,
    labelWidth: 100,
    fieldWidth: 160,
    baseCls: 'x-plain',
    defaultType: 'textfield',
    
    initComponent: function(){
        this.initMetas();
        CQCIS.form.DWRForm.superclass.initComponent.call(this);
        
        this.addEvents({
            /**
             * @event on load
             */
            "beforeload": true,
            "loadafter": true,
            /**
             * @event on save
             */
            "beforesave": true,
            "saveafter": true
        });
    },
    
    /** private */
    initMetas: function(){
        var items = [], records = [];
        var valTextFun = function(val){
            var re = /[^\u00A1-\uFFE5\w]/m;
            return re.test(val) ? '输入的内容包含非法字符！' : true;
        };
        for (var i = 0; i < this.metas.length; i++) {
            var m = this.metas[i];
            var o = Ext.applyIf(m.obj ||
            {}, {
                name: m.field,
                fieldLabel: m.desc,
                anchor: m.anchor || '95%'
            });
            var r = {
                name: m.field,
                type: (m.type ? m.type : 'string')
            };
            
            if (!o.isFormField) {
                switch (m.xtype) {
                    case 'date':
                        o.xtype = 'datefield';
                        o.format = m.format ? m.format : "Y-m-d";
                        o.readOnly = true;
                        r.type = 'date';
                        break;
                    case 'time':
                        o.xtype = 'timefield';
                        o.readOnly = true;
                        o.format = m.format ? m.format : "Y-m-d H:i:s";
                        r.type = 'date';
                        break;
                    case 'num':
                        o.xtype = 'numberfield';
                        // o.vtype = 'number';
                        break;
                    case 'check':
                        o.xtype = 'checkbox';
                        break;
                    case 'area':
                        o.xtype = 'textarea';
                        o.anchor = '94%';
                        break;
                    case 'pwd':
                        o.xtype = 'textfield';
                        o.inputType = 'password';
                        o.cls = 'password';
                        break;
                    case 'pwdv':
                        o.xtype = 'textfield';
                        o.inputType = 'password';
                        o.cls = 'password';
                        break;
                    case 'int':
                        o.vtype = 'int';
                        o.xtype = 'textfield';
                        r.type = 'int';
                        break;
                    default:
                        if (m.xtype) {
                            o.xtype = m.xtype;
                        } else {
                            o.xtype = 'textfield';
                        }
                        break;
                }
            }
            
            if (m.vtype) {
                if (m.vtype == 'valText') {
                    o.validator = valTextFun;
                } else {
                    o.vtype = m.vtype;
                }
            }
            o.width = this.fieldWidth;
            
            if (m.mapping) {
                r.mapping = m.mapping;
                o.mapping = m.mapping;
            }
            
            records[records.length] = r;
            if (!m.values) {
                o.msgTarget = 'side';
                items[items.length] = o;
            } else if (m.values.length > 0 && (o.xtype == 'radio' || o.xtype == 'checkbox')) {
                for (var j = 0; j < m.values.length; j++) {
                    var rd, val = m.values[j];
                    rd = Ext.apply({
                        value: val.id,
                        boxLabel: val.name
                    }, o);
                    rd.fieldLabel = (j === 0 ? m.desc : null);
                    if (j > 0) {
                        rd.labelSeparator = '';
                    }
                    items[items.length] = rd;
                }
            }
        }
        this.items = items;
        this.recordTypes = records;
    },
    
    getDs: function(){
        if (this.dwr && !this.ds) {
            this.ds = new CQCIS.data.DWRStore({
                dwr: {
                    call: this.dwr.load,
                    save: this.dwr.save ? this.dwr.save : this.dwr.update,
                    update: this.dwr.update ? this.dwr.update : this.dwr.save
                },
                fields: this.recordTypes,
                ownerCt: this
            });
            
            this.ds.on('load', function(scope, recodes){
                var recode = recodes[0];
                var data = recode ? recode.data : {};
                this.form.setValues(data);
                this.afterRemote();
                this.fireEvent('loadafter', data, this, scope);
            }, this);
            
            this.ds.on('save', function(scope, o){
                this.afterRemote();
                this.fireEvent('saveafter', o, this, scope);
            }, this);
        }
        
        return this.ds;
    },
    
    // private
    beforeRemote: function(waitMsg){
        if (waitMsg) {
            if (this.waitMsgTarget === true) {
                this.el.mask(waitMsg, 'x-mask-loading');
            } else if (this.waitMsgTarget) {
                this.waitMsgTarget = Ext.get(this.waitMsgTarget);
                this.waitMsgTarget.mask(waitMsg, 'x-mask-loading');
            } else {
                Ext.MessageBox.wait(waitMsg, '请稍候...');
            }
            this.doing = true;
        }
    },
    
    // private
    afterRemote: function(action, success){
        if (this.doing) {
            if (this.waitMsgTarget === true) {
                this.el.unmask();
            } else if (this.waitMsgTarget) {
                this.waitMsgTarget.unmask();
            } else {
                Ext.MessageBox.updateProgress(1);
                Ext.MessageBox.hide();
            }
            this.doing = false;
        }
    },
    
    // private
    doRemote: function(action){
        var valid = this.form.isValid();
        if (!valid) {
            CQCIS.msg('字段校验没通过,请查看窗口字段提示信息!');
        } else {
            this.beforeRemote('正在保存数据...');
            if (this.fireEvent("beforesave", this) !== false) {
                var arg = [this.getValues()];
                if (this.extendParams.length > 0) {
                    arg = arg.concat(this.extendParams);
                }
                this.getDs()[action]({
                    arg: arg
                });
            } else {
                this.afterRemote();
            }
        }
    },
    
    /**
     * @param params
     *
     * <pre>
     * null
     * 代表新增
     * object/array  修改
     * </pre>
     */
    load: function(params){
        if (this.doing === true) {
            CQCIS.msg('正在远程访问,请稍侯!');
        } else {
            if (params) {
                this.beforeRemote('正在读取数据...');
                params = params instanceof Array ? params : [params];
                if (this.fireEvent("beforeload", this, params) !== false) {
                    this.reset();
                    this.getDs().load({
                        arg: params
                    });
                }
            } else {
                // this.form.reset();
                this.form.isValid(); // 增加校验提示
            }
        }
    },
    
    /**
     * @param params
     *            FORM提交时基础属性
     */
    save: function(){
        if (this.doing === true) {
            CQCIS.msg('正在远程访问,请稍侯!');
        } else {
            this.doRemote('save');
        }
    },
    update: function(){
        if (this.doing === true) {
            CQCIS.msg('正在远程访问,请稍侯!');
        } else {
            this.doRemote('update');
        }
    },
    
    /** 重置 */
    reset: function(){
        this.afterRemote();
        this.form.reset();
    },
    
    /**
     * 获取FORM值对象
     *
     * @param {Boolean}
     *            asString
     * @return {Object}
     */
    getValues: function(asString){
        // var obj = this.form.getValues(asString);
        var obj = {};
        for (var i = 0; i < this.metas.length; i++) {
            var m = this.metas[i];
            var f = this.form.findField(m.field);
            
            if (m.field.indexOf("_") === 0) {
                continue;
            } else if (m.xtype == 'radio') {
                obj[m.field] = f.getGroupValue();
            } else if (m.xtype == 'hidden' && m.type == 'date') {
                obj[m.field] = f.getValue() ? new Date(f.getValue()) : new Date();
            } else {
                obj[m.field] = f.getValue();
            }
        }
        if (asString) {
            obj = Ext.urlEncode(obj);
        }
        if (this.baseParams && typeof this.baseParams == 'object') {
            if (asString) {
                obj = obj + '&' + Ext.urlEncode(this.baseParams);
            } else {
                Ext.apply(obj, this.baseParams);
            }
        }
        
        return obj;
    },
    
    /**
     * 获取FORM字段
     */
    findField: function(id){
        return this.form.findField(id);
    },
    
    setExtendParams: function(parms){
        this.extendParams = [];
        if (parms instanceof Array) {
            this.extendParams = this.extendParams.concat(parms);
        } else {
            this.extendParams.push(parms);
        }
    }
});
Ext.reg('rform', CQCIS.form.DWRForm);
